﻿using System;

using zijian666.Converts.Tools;

namespace zijian666.Converts.Core;

/// <summary>
/// 用于描述字符串分割规则
/// </summary>
public class StringSeparator
{
    /// <summary>
    /// 用于分割字符串的标识
    /// </summary>
    private readonly string[] _array;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="separators"></param>
    private StringSeparator(string[] separators) => _array = separators ?? throw new ArgumentNullException(nameof(separators));
    /// <summary>
    /// 隐式转换
    /// </summary>
    /// <param name="separator"></param>
    public static implicit operator StringSeparator(string separator)
        => new(string.IsNullOrEmpty(separator) ? ArrayHelper<string>.ENPTY : new[] { separator });
    /// <summary>
    /// 运算符 + 重载
    /// </summary>
    public static StringSeparator operator +(StringSeparator separator, string str)
    {
        if (separator is null)
        {
            return str;
        }
        if (string.IsNullOrEmpty(str))
        {
            return separator;
        }
        var array1 = separator._array;
        var array2 = new string[array1.Length];
        Array.Copy(array1, array2, array1.Length);
        array2[array1.Length] = str;
        return new(array2);
    }

    /// <summary>
    /// 获取第一个分隔符
    /// </summary>
    public string First => _array.Length == 0 ? "," : _array[0];

    /// <summary>
    /// 隐式转换
    /// </summary>
    /// <param name="separator"></param>
    public static implicit operator string[](StringSeparator separator)
        => separator is null ? ArrayHelper<string>.ENPTY : separator._array;
}
